package mwa.cs.ar.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mwa.cs.dao.ArDAO;
import mwa.cs.dao.CustHHDAO;
import mwa.cs.dao.CustMonthlyDAO;
import mwa.cs.dao.SMErrorLogDAO;
//import mwa.cs.dao.getBillnumber;
import mwa.cs.database.Database;
import mwa.cs.hh.biz.MeterFunction;
import mwa.cs.model.Ar;
import mwa.cs.model.SMErrorLog;
import mwa.cs.util.JDate;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * Servlet implementation class CS42003Srvl
 */
public class CS42003Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;
	private int vnUserId;
	private String vaUrlAddress;
	private String vaAgentBrowser;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS42003Srvl() {
        super();
        // TODO Auto-generated constructor stub
    }	
    
    @SuppressWarnings({ })
	public void processRequest(HttpServletRequest request,
	HttpServletResponse response) throws ServletException, IOException {
    	
    	vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());

    	vaUrlAddress = request.getParameter("url_address");
    	vaAgentBrowser = request.getParameter("agent_browser");
    	request.setCharacterEncoding("UTF-8");
   		response.setCharacterEncoding("UTF-8");
   		response.setContentType("text/JSON");
   		String vaProcessType = request.getParameter("methodType");
		if (vaProcessType.equals("getDataAR")){
			getDataAR(request, response);
		} else {
			saveData(request, response);
		}
	}
   	
    @SuppressWarnings("unchecked")
	public void saveData(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	
    	PrintWriter voOut = response.getWriter();
		JSONObject voObject = new JSONObject();
		Database db = new Database();
		Ar voAR = new Ar();
    	ArDAO voARDAO = new ArDAO(db);
		String vaBillNumber = request.getParameter("billNumber").trim();
		String vaStatus = "C";
		String vaVoidDate = JDate.getDate();
		String vaVoidTime = JDate.getTime();
		String vaReason = request.getParameter("reason").trim();
		String vaUpdateDate = JDate.getDate();
		String vaUpdateTime = JDate.getTime();
		
		voAR.setVaStatus(vaStatus);
		voAR.setVaViodDate(vaVoidDate);
		voAR.setVaVoidTime(vaVoidTime);
		voAR.setVnViodEmployee(vnUserId);
		voAR.setVaReason(vaReason);
		voAR.setVnUpdateUserId(vnUserId);
		voAR.setVaUpdateDate(vaUpdateDate);
		voAR.setVaUpdateTime(vaUpdateTime);
		try {
			db.beginTransaction();
			boolean vbResult = voARDAO.cancelAR(vaBillNumber, voAR);
			if (vbResult) {
				voObject.put("message", "success");
			} else {
				voObject.put("message", "fail");
			}
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS42003", JDate.getDate(), JDate.getTime(),vnUserId, "CS42003Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);	
			db.rollback();
			voObject.put("message", "fail");
		}
		db.close();
		voOut.print(voObject.toJSONString());
    }
    
    @SuppressWarnings("unchecked")
	public void getDataAR(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	
    	PrintWriter voOut = response.getWriter();
		JSONObject voObject = new JSONObject();
		Database db = new Database();
    	ArDAO voARDAO = new ArDAO(db);
    	DecimalFormat voFormatter = new DecimalFormat("#,##0.00");
		String vaPutBillNumber = request.getParameter("billNumber");
		String vaAccount = "";
		String vaZoneName = "";
		String vaRvoOuteDescription = "";
		String vaSequence = "";
		String vaFullName = "";
		String vaCustomerClass = "";
		String vaAddress = ""; 
		String vaBillNumber = "";
		String vaAccountReceivableData = "";
		String vaConsumption = "";
		String vaWaterCharge = "";
		String vaWaterFee = "";
		String vaVatAmount = "";
		String vaBillAmount = "";
		String vaGarbageCharge = "";
		String vaWasteWaterCharge = "";
		String vaOtherCharge = "";
		String vaTotalAmount = "";
		String vaStatus = "";
		String vaReceiveDate = "";
		
		Map<String, Object> voMapAR = new HashMap<String, Object>();
		voMapAR = voARDAO.searchARForCancel(vnSiteId, vaPutBillNumber);
		if (voMapAR == null) {
			voObject.put("message", "resultNull");
		} else {
			vaStatus = ""+ voMapAR.get("STATUS");
			vaReceiveDate = ""+ voMapAR.get("RECEIVE_DATE");
			if (vaStatus.equals("0")) {
				voObject.put("message", "status");
			} else if (!vaReceiveDate.equals("null")) {
				voObject.put("message", "receiveDate");
			} else {
				vaAccount = ""+ voMapAR.get("ACCOUNT");
				vaZoneName = ""+ voMapAR.get("ZONE_NAME");
				vaRvoOuteDescription = ""+ voMapAR.get("ROUTE_DESCRIPTION");
				vaSequence = ""+ voMapAR.get("SEQ");
				vaFullName = ""+ voMapAR.get("FULL_NAME");
				vaCustomerClass = ""+ voMapAR.get("DESCRIPTION");
				vaAddress = ""+ voMapAR.get("ADDRESS");
				vaBillNumber = ""+ voMapAR.get("BILL_NUMBER");
				vaAccountReceivableData = ""+ voMapAR.get("ACCOUNT_RECEIVABLE_DATE");
				vaConsumption = ""+ voMapAR.get("CONSUMPTION");
				vaOtherCharge = ""+ voMapAR.get("WATER_CHARGE");
				vaWaterFee = ""+ voMapAR.get("WATER_FEE");
				vaAccount = ""+ voMapAR.get("VAT_AMOUNT");
				vaBillAmount = ""+ voMapAR.get("BILL_AMOUNT");
				vaGarbageCharge = ""+ voMapAR.get("GARBAGE_CHARGE");
				vaWasteWaterCharge = ""+ voMapAR.get("WASTEWATER_CHARGE");
				vaOtherCharge = ""+ voMapAR.get("OTHER_CHARGE");
				vaTotalAmount = ""+ voMapAR.get("TOTAL_AMOUNT");
		    			
				voObject.put("account", vaAccount);
				voObject.put("zoneName", vaZoneName);
				voObject.put("rvoOuteDescription", vaRvoOuteDescription);
				voObject.put("sequence", vaSequence);
				voObject.put("fullName", vaFullName);
				voObject.put("customerClass", vaCustomerClass);
				voObject.put("address", vaAddress);
				voObject.put("billNumber", vaBillNumber);
				voObject.put("accountReceivableData", vaAccountReceivableData);
				voObject.put("consumption", vaConsumption);
				voObject.put("waterCharge", voFormatter.format(Double.parseDouble(vaOtherCharge)));
				voObject.put("waterFee", voFormatter.format(Double.parseDouble(vaWaterFee)));
				voObject.put("vatAmount", voFormatter.format(Double.parseDouble(vaAccount)));
				voObject.put("billAmount", voFormatter.format(Double.parseDouble(vaBillAmount)));
				voObject.put("garbageCharge", voFormatter.format(Double.parseDouble(vaGarbageCharge)));
				voObject.put("wasteWaterCharge", voFormatter.format(Double.parseDouble(vaWasteWaterCharge)));
				voObject.put("otherCharge", voFormatter.format(Double.parseDouble(vaOtherCharge)));
				voObject.put("totalAmount", voFormatter.format(Double.parseDouble(vaTotalAmount)));
			}
		}
		db.close();
    	voOut.print(voObject.toJSONString());
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

}
